package struct;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import action.Action;
import entity.XmlBean;
import form.ActionFrom;
import form.FullForm;



/**
 * Servlet implementation class ActionServlet
 */
/**
 * Servlet implementation class ActionServlet
 */
@WebServlet("/ActionServlet")
public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		
		String username = request.getParameter("name");	
		request.setAttribute("un", username);
		
		String path = this.getPath(request.getServletPath());
		@SuppressWarnings("unchecked")
		Map<String,XmlBean> map =(Map<String,XmlBean>) this.getServletContext().getAttribute("xml");
		XmlBean xml = map.get(path);
		String formclass = xml.getFormClass();
		String url = "";
		try {
			ActionFrom form = FullForm.full(formclass, request);
			String actionClass = xml.getActionClass();
			Action action = null;
			Class clazz = Class.forName(actionClass);
			action = (Action)clazz.newInstance();
			url = action.execute(request, form, xml.getActionForward());
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		RequestDispatcher dis = request.getRequestDispatcher(url);
		dis.forward(request , response);
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	private String getPath(String path)
	{
		return path.split("\\.")[0];
	}
	
	
	


}